package com.zhiche.lisa.bms.service.driver.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zhiche.lisa.bms.dao.mapper.driver.VehicleClassifyMapper;
import com.zhiche.lisa.bms.dao.model.driver.BaseCvTankvolume;
import com.zhiche.lisa.bms.dao.model.driver.PriceconfOc;
import com.zhiche.lisa.bms.dao.model.driver.VehicleClassify;
import com.zhiche.lisa.bms.pojo.vo.driver.VehicleClassifyVO;
import com.zhiche.lisa.bms.service.driver.IBaseCvTankvolumeService;
import com.zhiche.lisa.bms.service.driver.IPriceconfOcService;
import com.zhiche.lisa.bms.service.driver.IVehicleClassifyService;
import com.zhiche.lisa.core.supports.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 车型分类表 服务实现类
 * </p>
 *
 * @author zhaoguixin
 * @since 2018-08-30
 */
@Service
@Slf4j
public class VehicleClassifyServiceImpl extends ServiceImpl<VehicleClassifyMapper, VehicleClassify> implements IVehicleClassifyService {

    @Autowired
    private IBaseCvTankvolumeService baseCvTankvolumeService;

    @Autowired
    private IPriceconfOcService priceconfOcService;

    /**
     * 分页查询车型
     *
     * @param pageVO
     * @return
     */
    @Override
    public Page<VehicleClassifyVO> listByPage(Page<VehicleClassifyVO> pageVO) {
        if (pageVO == null) {
            return null;
        }
        pageVO.setOrderByField("create_time");
        pageVO.setAsc(false);
        EntityWrapper<VehicleClassifyVO> ew = whereCondition(pageVO);
        List<VehicleClassifyVO> listVO = baseMapper.selectByConditions(pageVO, ew);
        pageVO.setRecords(listVO);
        return pageVO;
    }

    /**
     * 添加车型信息
     *
     * @param vehicleClassifyVO
     * @param br
     * @return
     */
    @Override
    public Integer add(VehicleClassifyVO vehicleClassifyVO, BindingResult br) {
        log.info("VehicleClassifyServiceImpl.add param : {}", vehicleClassifyVO);

        if (Objects.isNull(vehicleClassifyVO)) {
            log.error("VehicleClassifyServiceImpl.add param form must not be null");
            throw new BaseException("车型分类表单不能为空");
        }

        //验证表单
        verificationForm(br);
        //业务验证 车型分类编码唯一
        verificationBusiness(vehicleClassifyVO);

        VehicleClassify vehicleClassify = new VehicleClassify();
        BeanUtils.copyProperties(vehicleClassifyVO, vehicleClassify);
        vehicleClassify.setEnable(1);
        this.insert(vehicleClassify);
        return vehicleClassify.getId();
    }

    /**
     * 更新车型信息
     *
     * @param vehicleClassifyVO
     * @param br
     * @return
     */
    @Override
    public Boolean update(VehicleClassifyVO vehicleClassifyVO, BindingResult br) {
        log.info("VehicleClassifyServiceImpl.add param : {}", vehicleClassifyVO);

        if (Objects.isNull(vehicleClassifyVO)) {
            log.error("VehicleClassifyServiceImpl.add param form must not be null");
            throw new BaseException("车型分类表单不能为空");
        }

        //验证表单
        verificationForm(br);

        //业务验证 车型分类编码唯一
        verificationBusiness(vehicleClassifyVO);

        VehicleClassify vehicleClassify = new VehicleClassify();
        BeanUtils.copyProperties(vehicleClassifyVO, vehicleClassify);
        return this.updateById(vehicleClassify);
    }

    /**
     * 更新车型可用还是不可用
     *
     * @param id
     * @param enableOrDisabled
     * @return
     */
    @Override
    public Boolean enableOrDisabled(Integer id, Boolean enableOrDisabled) {
        log.info("VehicleClassifyServiceImpl.enableOrDisabled params id: {}, enableOrDisabled: {}", id, enableOrDisabled);
        if (Objects.isNull(id)) {
            log.error("VehicleClassifyServiceImpl.enableOrDisabled param id must not be null");
            throw new BaseException("车型分类编码不能为空");
        }

        VehicleClassify classify = this.selectById(id);
        if (Objects.isNull(classify)) {
            log.error("车型分类信息不存在");
            throw new BaseException("车型分类信息不存在");
        }

        if (enableOrDisabled) {
            classify.setEnable(1);
        } else {
            classify.setEnable(0);
        }
        return this.updateById(classify);
    }

    /**
     * 根据id得到车型信息
     *
     * @param id
     * @return
     */
    @Override
    public VehicleClassifyVO getById(Integer id) {
        VehicleClassify vehicleClassify = this.selectById(id);
        VehicleClassifyVO vehicleClassifyVO = new VehicleClassifyVO();
        BeanUtils.copyProperties(vehicleClassify, vehicleClassifyVO);
        return vehicleClassifyVO;
    }

    /**
     * 删除车辆信息
     *
     * @param id
     * @return
     * @throws BaseException
     */
    @Override
    public Boolean del(Integer id) throws BaseException {
        log.info("VehicleClassifyServiceImpl.del param : {}", id);

        if (Objects.isNull(id) || id.equals(0)) {
            log.error("VehicleClassifyServiceImpl.del param id must not be null");
            throw new BaseException("主键不能为空");
        }

        VehicleClassify vehicleClassify = this.selectById(id);
        if (Objects.isNull(vehicleClassify)) {
            log.error("VehicleClassifyServiceImpl.del param id must not be null");
            throw new BaseException("主键不能为空");
        }

        //判断是否在车型油箱容积中使用
        EntityWrapper<BaseCvTankvolume> ewBC = new EntityWrapper<>();
        ewBC.eq("cv_type_id", vehicleClassify.getVehicleClassifyId());
        List<BaseCvTankvolume> list = baseCvTankvolumeService.selectList(ewBC);
        if (CollectionUtils.isNotEmpty(list)) {
            log.error("VehicleClassifyServiceImpl.del associated with BaseCvTankvolume");
            throw new BaseException("请先移除油箱容积的记录");
        }

        EntityWrapper<PriceconfOc> ewPF = new EntityWrapper<>();
        ewPF.eq("vehicle_type_id", id);
        List<PriceconfOc> listPf = priceconfOcService.selectList(ewPF);
        if (CollectionUtils.isNotEmpty(list)) {
            log.error("VehicleClassifyServiceImpl.del associated with BaseCvTankvolume");
            throw new BaseException("请先移除油箱容积的记录");
        }

        return this.deleteById(id);
    }

    /**
     * 根据名称查找
     *
     * @param key
     * @return
     */
    @Override
    public List<VehicleClassifyVO> listByName(String key) {
        List<VehicleClassifyVO> listVO = Lists.newArrayList();
        EntityWrapper<VehicleClassify> ew = new EntityWrapper<>();
        ew.like("vehicle_classify_name", key).eq("`enable`", 1);
        List<VehicleClassify> list = this.selectList(ew);
        list.forEach(vehicleClassify -> {
            VehicleClassifyVO vo = new VehicleClassifyVO();
            BeanUtils.copyProperties(vehicleClassify, vo);
            listVO.add(vo);
        });
        return listVO;
    }

    /**
     * 根据车型编码获取油类型
     *
     * @param code
     * @return
     */
    @Override
    public VehicleClassify getVehicleClassfyByVmCode(String code) {
        if (StringUtils.isNotBlank(code)) {
            EntityWrapper<VehicleClassify> ew = new EntityWrapper<>();
            ew.like("vehicle_classify_id", code).eq("`enable`", 1);
            List<VehicleClassify> classifyList = this.selectList(ew);
            if (CollectionUtils.isNotEmpty(classifyList)) {
                return classifyList.get(0);
            }
        }
        return null;
    }

    /**
     * 查询条件
     *
     * @param page
     * @return
     */
    private EntityWrapper<VehicleClassifyVO> whereCondition(Page<VehicleClassifyVO> page) {
        EntityWrapper<VehicleClassifyVO> ew = new EntityWrapper<>();
        //查询条件
        if (Objects.nonNull(page.getCondition())) {
            //分类名称
            if (Objects.nonNull(page.getCondition().get("vehicleClassifyName")) && StringUtils.isNotEmpty(page.getCondition().get("vehicleClassifyName").toString())) {
                ew.like("vehicle_classify_name", page.getCondition().get("vehicleClassifyName").toString().trim());
            }
            // 燃油类型
            if (Objects.nonNull(page.getCondition().get("fuelTypeId")) && StringUtils.isNotEmpty(page.getCondition().get("fuelTypeId").toString())) {
                ew.eq("fuel_type_id", page.getCondition().get("fuelTypeId").toString().trim());
            }
        }
        return ew;
    }


    /**
     * 验证表单
     *
     * @param br
     */
    private void verificationForm(BindingResult br) {
        if (Objects.isNull(br)) {
            log.error("VehicleClassifyServiceImpl.verificationForm error br is null");
            throw new BaseException("BindingResult is null");
        } else if (br.hasErrors()) {
            List<ObjectError> list = br.getAllErrors();
            log.error("VehicleClassifyServiceImpl.add error : {}", list.get(0).getDefaultMessage());
            throw new BaseException(list.get(0).getDefaultMessage());
        }
    }

    /**
     * 验证表单
     *
     * @param vehicleClassifyVO
     */
    private void verificationBusiness(VehicleClassifyVO vehicleClassifyVO) {
        log.info("VehicleClassifyServiceImpl.verificationBusinessByAdd param : {}", vehicleClassifyVO);

        if (Objects.isNull(vehicleClassifyVO)) {
            log.error("VehicleClassifyServiceImpl.verificationBusinessByAdd param form must not be null");
            throw new BaseException("车型分类表单不能为空");
        }

        this.verificationClassifyIdOrClassifyNameUnique(vehicleClassifyVO.getId(), vehicleClassifyVO.getVehicleClassifyName(), vehicleClassifyVO.getVehicleClassifyId());
    }

    /**
     * 判断是否存在
     *
     * @param id
     * @param vehicleClassifyName
     * @param vehicleClassifyId
     */
    private void verificationClassifyIdOrClassifyNameUnique(Integer id, String vehicleClassifyName, String vehicleClassifyId) {
        log.info("VehicleClassifyServiceImpl.selectByVehicleClassifyId param : {}", vehicleClassifyId);

        if (StringUtils.isEmpty(vehicleClassifyId)) {
            log.error("VehicleClassifyServiceImpl.selectByVehicleClassifyId param vehicleClassifyId must not be null");
            throw new IllegalArgumentException("车型分类编码不能为空");
        }

        EntityWrapper<VehicleClassify> ew = new EntityWrapper<>();
        ew.eq("vehicle_classify_id", vehicleClassifyId);
        VehicleClassify vehicleClassify = this.selectOne(ew);
        if (Objects.nonNull(vehicleClassify)) {
            if (!vehicleClassify.getId().equals(id)) {
                log.error("VehicleClassifyServiceImpl.verificationBusinessByAdd business error");
                throw new BaseException("车型分类编码已经存在");
            }
        }

        EntityWrapper<VehicleClassify> ew1 = new EntityWrapper<>();
        ew1.eq("vehicle_classify_name", vehicleClassifyName);
        vehicleClassify = this.selectOne(ew1);
        if (Objects.nonNull(vehicleClassify)) {
            if (!vehicleClassify.getId().equals(id)) {
                log.error("VehicleClassifyServiceImpl.verificationBusinessByAdd business error");
                throw new BaseException("车型分类名称已经存在");
            }
        }
    }
}
